package com.baiyang.server.runner;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baiyang.server.annotation.Jurisdiction;
import com.baiyang.server.dao.system.JurisdictionInterfaceDao;
import com.baiyang.server.model.system.JurisdictionInterface;
import com.baiyang.server.tools.DataTool;


/**
 * 初始化权限
 * @author XVX
 * 
 * 将根据@Jurisdiction和@RequestMapping注解获取权限信息
 * 将获取到的合法权限信息插入到数据库中
 */
@Component
@Order(2)
@Transactional
public class InitJurisdiction implements ApplicationRunner  {
	@Autowired
	private ApplicationContext applicationContext;
	@Autowired
	private JurisdictionInterfaceDao dao = null;
	@Override
	public void run(ApplicationArguments args) throws Exception {
		// TODO Auto-generated method stub
		Object objecy = applicationContext.getBean(InitJurisdiction.class);
		if(this == applicationContext.getBean(InitJurisdiction.class)) {
			System.err.println("true");
		}
		dao.delete(null);
		String[] beans = applicationContext.getBeanDefinitionNames();
		List<JurisdictionInterface> list = new ArrayList<JurisdictionInterface>();
		for (String name : beans) {
			String url = "";
			String group = "";
			Class<? extends Object> obj = applicationContext.getBean(name).getClass();
			//如果是个接口
			if(obj.isAnnotationPresent(RestController.class)){
				//获取接口
				url += obj.getAnnotation(RequestMapping.class).value()[0];
				group = obj.getAnnotation(Jurisdiction.class).value();
				Method[] methods = obj.getDeclaredMethods();
				for (Method method : methods) {
					String Interface = "";
					if(method.isAnnotationPresent(RequestMapping.class)) {
						Interface = url + method.getAnnotation(RequestMapping.class).value()[0];
					}
					String jurisdiction = "";
					if(method.isAnnotationPresent(Jurisdiction.class)) {
						jurisdiction = method.getAnnotation(Jurisdiction.class).value();
					}
					JurisdictionInterface jurisdictionInterface = new JurisdictionInterface();
					jurisdictionInterface.setJurisdictionGroup(group);
					jurisdictionInterface.setInterfaceUrl(Interface);
					jurisdictionInterface.setJurisdiction(jurisdiction);
					jurisdictionInterface.setId(DataTool.createUUID());
					list.add(jurisdictionInterface);
				}
			}
		}
		dao.insertBatch(list);
	}

}
